/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.JD.ExportToExcel;

import javax.swing.JTable;

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author admin
 */
public class ExportToExcel extends javax.swing.JFrame {

    public void saveToExcel(JTable table) {

        String fileName = "";
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setBounds(1, 1, 100, 100);

        switch (fileChooser.showSaveDialog(this)) {
            case JFileChooser.APPROVE_OPTION:

                fileName = fileChooser.getSelectedFile() + "";
               


                break;

            case JFileChooser.CANCEL_OPTION:
                JOptionPane.showMessageDialog(this, "Cancelled",
                        "FCDemo",
                        JOptionPane.OK_OPTION);
                break;

            case JFileChooser.ERROR_OPTION:
                JOptionPane.showMessageDialog(this, "Error",
                        "FCDemo",
                        JOptionPane.OK_OPTION);
        }




        javax.swing.table.DefaultTableModel defaultTableModel = (javax.swing.table.DefaultTableModel) table.getModel();






        int cellCount = defaultTableModel.getColumnCount();
        int rowCount = defaultTableModel.getRowCount();


        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Test Sheet");





        Row header = sheet.createRow(0);

        for (int i = 0; i < cellCount; i++) {

            sheet.setColumnWidth(i, 6000);
            header.createCell(i).setCellValue(defaultTableModel.getColumnName(i));
        }



        for (int i = 0; i < rowCount; i++) {
            header = sheet.createRow(i + 1);

            for (int j = 0; j < cellCount; j++) {

                sheet.setColumnWidth(j, 6000);
                header.createCell(j).setCellValue(defaultTableModel.getValueAt(i, j) + "");


            }


        }





//        }


        try {
            FileOutputStream out =
                    new FileOutputStream(new File(fileName + ".xls"));
            workbook.write(out);
            out.close();

            JOptionPane.showMessageDialog(null, "File Save To " + fileName + ".xls");


        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}
